package com.heima.gateway.auth;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author : 王苑
 * @Date : Created in 2022年08月01日
 * app网关  全局过滤器
 * 作用：对token  （jwt令牌）进行校验
 */
public class AuthFitler implements GlobalFilter, Ordered {

    /**
     * 过滤器逻辑:
     * 前后端约定：将JWT令牌设置的设置到请求头：token中   企业中约定俗成的：Authorization
     * 得到客户端提交令牌，解析令牌，获取载荷中用户信息，将用户ID设置到请求头，将请求路由到目标微服务
     *
     * @param exchange 封装请求响应对象
     * @param chain    过滤器链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.通过exchange获取请求，响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {
            //2.获取客户端请求地址，放行登录请求
            String path = request.getURI().getPath();
            if (path.contains("/login")) {
                //登录请求直接放行
                return chain.filter(exchange);
            }
            //3.该请求需要进行令牌校验 从请求头 token中获取令牌 解析令牌
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //4.调用工具类解析令牌（校验令牌是否有效，在有效期内）
            //4.1 获取令牌中载荷信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //4.2 获取是否令牌有效
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == -1 || i == 0) {
                //令牌有效  从载荷中获取用户ID 设置到请求头中
                Object userId = claimsBody.get("userId");
                Object userName = claimsBody.get("userName");
                if (Integer.parseInt(userId.toString()) != 0) {
                    //说明用户采用 手机号密码登录
                    request.mutate().header("userId", userId.toString());
                    request.mutate().header("userName", userName.toString());
                }
                Object equipmentId = claimsBody.get("equipmentId");
                if (equipmentId != null) {
                    //说明用户 选择设备登录
                    request.mutate().header("userId", userId.toString());
                    request.mutate().header("equipmentId", equipmentId.toString());
                }
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //其他请求直接返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

